package com.tomtop.core.logging;

import java.lang.reflect.Method;

import javax.servlet.http.HttpServletRequest;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.ResponseBody;

import com.tomtop.core.Context;
import com.tomtop.core.utils.MapUtils;

/**
 * Aop 访问日志
 * 
 * @author lenovo
 *
 */
@Aspect
@Order(1)
@Component
public class ControllerLogAop {


	@Pointcut("within(@org.springframework.web.bind.annotation.RestController *)")
	public void restController(){}
	
	@Pointcut("within(@org.springframework.stereotype.Controller *)")
	public void controller(){}

	@Around("restController()")
	public Object restRecordSysLog(ProceedingJoinPoint point) throws Throwable {
		Context.isRest(true);
		return recordSysLog(point);
	}
	
	@Around("controller()")
	public Object otherRecordSysLog(ProceedingJoinPoint point) throws Throwable {
        Method method = ((MethodSignature) point.getSignature()).getMethod();
    	Class<?> targetClass = point.getTarget().getClass();
    	ResponseBody classannotation = AnnotationUtils.findAnnotation(targetClass, ResponseBody.class) ;
    	ResponseBody annotation = AnnotationUtils.findAnnotation(method, ResponseBody.class) ;
    	Context.isRest(annotation!=null||classannotation!=null);
		return recordSysLog(point);
	}
	
	public Object recordSysLog(ProceedingJoinPoint point) throws Throwable {
		long starttime = System.currentTimeMillis();
		try {
			return point.proceed();
		} finally {
			long runtime = System.currentTimeMillis() - starttime;
			
			String methodName = point.getSignature().getName();
			String className = point.getTarget().getClass().getName();
			HttpServletRequest request = Context.getRequest();
			String  bfparams= MapUtils.n(request.getParameterMap()).array((k,v)->{return k+"="+v;}).join("&");
			RunTimeLog.log(runtime," [方法]:{}.{},[参数]:{}", className, methodName, bfparams,runtime);
		}
	}

}
